# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2022/9/1
# @Author  : moe@miku39.fun
# @File    : FFmpeg.py
# @Software: PyCharm
import os
import subprocess


class FFmpegOperation:
    @classmethod
    def exist(cls, ffmpeg_path="ffmpeg"):
        try:
            if (
                subprocess.run(
                    [ffmpeg_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE
                ).returncode
                != 1
            ):
                assert FileNotFoundError
            return True
        except FileNotFoundError:
            return False

    @classmethod
    def existFFmpeg(cls, path=""):
        system = os.name
        if system == "posix":
            if cls.exist():
                return "ffmpeg"
            return False
        elif system == "nt":
            # 检测环境变量是否配置FFmpeg
            if cls.exist():
                return "ffmpeg"
            # 检测指定的文件是否为FFmpeg软件
            elif os.path.isfile(path):
                if cls.exist(path):
                    return path
            # 检测指定的目录下是否有FFmpeg软件
            elif os.path.isdir(path):
                filePath = os.path.join(path, "ffmpeg.exe")
                if os.path.isfile(filePath):
                    if cls.exist(filePath):
                        return filePath
            else:
                return False

    @classmethod
    def concat(cls, file, sub_file):
        if len(sub_file) == 1:
            os.rename(sub_file[0], file)
        else:
            with open(file=file, mode="ab") as finalFile:
                for each in sub_file:
                    with open(file=each, mode="rb") as f:
                        finalFile.write(f.read())
        return True

    @classmethod
    def merge(cls, ffmpeg, video_path, audio_path, final_path):
        cmd = [os.path.normpath(ffmpeg)]
        cmd.extend(
            ["-i", video_path, "-i", audio_path, "-codec", "copy", "-y", final_path]
        )
        subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
